package com.shujia.indicators.core;

import com.shujia.indicators.utils.SparkUtils;
import org.apache.spark.api.java.function.MapFunction;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SaveMode;
import org.apache.spark.sql.SparkSession;
import scala.Tuple2;
import scala.collection.Seq;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;

public class GrowthEtl {
    public static void main(String[] args) {
        SparkSession sparkSession = SparkUtils.initSession();
        growthEtl(sparkSession);

    }
    private static void growthEtl(SparkSession sparkSession){
        LocalDate localDate = LocalDate.of(2019, 11, 30);

        Date now = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat foramt = new SimpleDateFormat("yyyy-MM-dd");
        calendar.setTime(now);
        calendar.add(Calendar.DATE,-7);
        Date sevenDayBefore = calendar.getTime();
        String format = foramt.format(sevenDayBefore);
        String sql ="select t1.*,t2.totalOrderCount,t2.gmv" +
                "from (select date_format(create_time, 'yyyy-MM-dd') as day ," +
                "count(id) as newRegCount,max(id) as totalMemberCount" +
                "from bigdata005_user_portraits_dim.dim_t_member where create_time >= '"+format+"'" +
                " group by date_format(create_time, 'yyyy-MM-dd') order by day) t1 join "+
        "(select date_format(create_time, 'yyyy-MM-dd') as day ," +
                "max(order_id) as totalOrderCount,sum(origin_price) as gmv" +
                "from bigdata005_user_portraits_dwd.dwd_t_order where create_time >='"+format+"'" +
                " group by date_format(create_time, 'yyyy-MM-dd')) t2" +
                "on t1.day = t2.day";
        Dataset<Row> dataset = sparkSession.sql(sql);

        dataset.write().format("jdbc")
                .mode(SaveMode.Append)
                .option("url","jdbc:mysql://localhost:3306/bigdata005?useSSL=false&useUnicode=true&characterEncoding=UTF-8")
                .option("dbtable","day_increase")
                .option("user","bigdata005")
                .option("password","ShuJia666777...")
                .option("driver","com.mysql.cj.jdbc.Driver")
                .save();

    }
}
